"""
Configuration management for ccwork.
"""

import json
import os
from pathlib import Path
from typing import Dict, Any, Optional


def get_config_file_path() -> Path:
    """Get the path to the configuration file."""
    config_dir = Path.home() / '.ccwork'
    config_dir.mkdir(exist_ok=True)
    return config_dir / 'config.json'


def save_default_config(config: Dict[str, Any]) -> None:
    """Save configuration as default."""
    config_file = get_config_file_path()
    
    # Only save relevant configuration options
    default_config = {}
    
    # CLI options that can be saved as defaults
    saveable_options = [
        'claude_dir', 'hours_back', 'show_inactive', 'workdir', 
        'port', 'host', 'debug'
    ]
    
    for option in saveable_options:
        if hasattr(config, option):
            value = getattr(config, option)
            if value is not None:  # Only save non-None values
                default_config[option] = value
    
    try:
        with open(config_file, 'w') as f:
            json.dump(default_config, f, indent=2)
        print(f"✅ Saved default configuration to {config_file}")
        
        # Show what was saved
        if default_config:
            print("📋 Saved settings:")
            for key, value in default_config.items():
                if key == 'claude_dir':
                    print(f"   --claude-dir: {value}")
                elif key == 'hours_back':
                    print(f"   --hours-back: {value}")
                elif key == 'show_inactive':
                    print(f"   --show-inactive: {value}")
                elif key == 'workdir':
                    print(f"   --workdir: {value}")
                elif key == 'port':
                    print(f"   --port: {value}")
                elif key == 'host':
                    print(f"   --host: {value}")
                elif key == 'debug':
                    print(f"   --debug: {value}")
        
    except (IOError, OSError) as e:
        print(f"❌ Error saving configuration: {e}")


def load_default_config() -> Optional[Dict[str, Any]]:
    """Load default configuration."""
    config_file = get_config_file_path()
    
    if not config_file.exists():
        return None
    
    try:
        with open(config_file, 'r') as f:
            config = json.load(f)
        return config
    except (IOError, OSError, json.JSONDecodeError) as e:
        print(f"⚠️  Warning: Could not load default configuration: {e}")
        return None


def apply_default_config(args, default_config: Dict[str, Any]) -> None:
    """Apply default configuration to argparse namespace, but don't override explicit arguments."""
    
    # Check which arguments were explicitly provided by the user
    # We'll only apply defaults for arguments that weren't explicitly set
    import sys
    explicit_args = set()
    
    # Parse command line to see what was explicitly provided
    argv = sys.argv[1:]
    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg.startswith('--'):
            arg_name = arg[2:].replace('-', '_')
            explicit_args.add(arg_name)
            
            # Skip argument value if present
            if i + 1 < len(argv) and not argv[i + 1].startswith('--'):
                i += 1
        elif arg.startswith('-') and len(arg) == 2:
            # Handle short options if we add any
            pass
        i += 1
    
    # Apply defaults only for non-explicit arguments
    for key, value in default_config.items():
        if key not in explicit_args:
            if not hasattr(args, key) or getattr(args, key) is None or getattr(args, key) == False:
                setattr(args, key, value)


def show_current_config() -> None:
    """Display current default configuration."""
    config = load_default_config()
    
    if not config:
        print("📋 No default configuration found. Use --default with other options to save a configuration.")
        return
    
    print("📋 Current default configuration:")
    for key, value in config.items():
        option_name = key.replace('_', '-')
        print(f"   --{option_name}: {value}")


def clear_default_config() -> None:
    """Clear the default configuration."""
    config_file = get_config_file_path()
    
    if config_file.exists():
        try:
            config_file.unlink()
            print("✅ Cleared default configuration")
        except (IOError, OSError) as e:
            print(f"❌ Error clearing configuration: {e}")
    else:
        print("📋 No default configuration to clear")


def has_non_default_args(args) -> bool:
    """Check if any non-default arguments are provided."""
    # Arguments that indicate actual work to be done (not just default management)
    work_args = [
        'serve', 'stop', 'show_inactive', 'workdir', 'json', 
        'claude_dir', 'hours_back', 'port', 'host', 'debug'
    ]
    
    for arg in work_args:
        if hasattr(args, arg):
            value = getattr(args, arg)
            # Check if argument has a non-default value
            if arg == 'port' and value != 8080:
                return True
            elif arg == 'host' and value != 'localhost':
                return True
            elif arg in ['serve', 'stop', 'show_inactive', 'json', 'debug'] and value:
                return True
            elif arg in ['claude_dir', 'hours_back', 'workdir'] and value is not None:
                return True
    
    return False